package LC.nums.minSubArrayLen;

public class LC76 {
    public static void main(String[] args) {
        String s = "ADOBECODEBANC";
        String t = "ABC";
        System.out.println(minWindow(s, t));
        System.out.println(Solution.minWindow(s, t));
    }

    /**
     * @param s
     * @param t
     * @return
     */
    public static String minWindow(String s, String t) {
        char[] chars = s.toCharArray();
        char[] chart = t.toCharArray();
        int sLength = chars.length, tLength = chart.length;
        String res = "";
        int countMin = 0;
        int[] hash = new int[128];

        for (int i = 0; i < tLength; i++) {
            hash[chart[i]]--;
        }

        for (int fastIndex = 0, slowIndex = 0; fastIndex < sLength; fastIndex++) {
            hash[chars[fastIndex]]++;
            if (hash[chars[fastIndex]] <= 0) countMin++;
            while (countMin == tLength && hash[chars[slowIndex]] > 0) {
                hash[chars[slowIndex++]]--;
            }
            if (countMin == tLength) {
                if (res.equals("") || res.length() > fastIndex - slowIndex + 1) {
                    res = s.substring(slowIndex, fastIndex + 1);
                }
            }
        }
        return res;
    }
}

class Solution {
    /**
     * @param s
     * @param t
     * @return
     */
    public static String minWindow(String s, String t) {
        //字符串转回字符数组
        char[] chars = s.toCharArray();
        char[] chart = t.toCharArray();
        int sLength = chars.length, tLength = chart.length;
        //如果 s 中不存在涵盖 t 所有字符的子串，则返回空字符串 ""
        String res = "";
        //最小子串，计数变量
        int countMin = 0;
        //利用ASCII码来映射，t中含有的字符--
        int[] hash = new int[128];

        //t中含有的字符,hash数组中赋值-n，t中可能重复字符
        for (int i = 0; i < tLength; i++) {
            hash[chart[i]]--;
        }

        //开始判断
        for (int fastIndex = 0, slowIndex = 0; fastIndex < sLength; fastIndex++) {
            //s中有，相应的位置++
            hash[chars[fastIndex]]++;
            //这个位置映射的数字要是还是小于0，表明有相同的字符
            if (hash[chars[fastIndex]] <= 0) countMin++;
            //如果这个子字符串已经有了所有的t中的字符,映射位置flag数值还原
            while (countMin == tLength && hash[chars[slowIndex]] > 0) {
                hash[chars[slowIndex++]]--;
            }
            //如果计数等于t的长度，返回结果
            if (countMin == tLength) {
                //判断是否是不存在
                if (res.equals("") || res.length() > fastIndex - slowIndex + 1) {
                    res = s.substring(slowIndex, fastIndex + 1);
                }
            }
        }
        return res;
    }
}